const http = require("http");
const fs = require("fs");
const path = require("path");

var pagePath = path.join(__dirname, "/index.html");
var iconParh = path.join(__dirname, "/icon.png");
function parseUrl(urlStr){
    var index = urlStr.indexOf("?");
    var pathName = "";
    if(index == -1){
        pathName = urlStr;
    }else{
        pathName = urlStr.slice(0,index);
        args = urlStr.slice(index+1);
        var argArr = args.split("&");
        var argObj = {};
        for(var i=0; i<argArr.length; i++){
            argObj[argArr[i].split("=")[0]] = argArr[i].split("=")[1];
        }
        console.log(argObj);
    }
    return{
        pathName: pathName,
        argObj: argObj
    }
}

function router(urlObj, req, res){
    if(urlObj.pathName.indexOf(".png") > 0 || urlObj.pathName.indexOf(".jpg") > 0){
        urlObj.pathName = "getimgdata";
    }
    switch(urlObj.pathName) {
        case "/":
            showIndex(res);
            break;
        case "getimgdata":
            resImage(res);
            break;
        case "/getlist":
            showlist(res);
            break;
        case "/del":
            deleteFile(urlObj.argObj,res);
            break;
    }
}

function showIndex(res){
    var fileContent = fs.readFileSync(pagePath);
    res.writeHead(200, {"Content-Type": "text/html;charset=utf-8"});
    res.write(fileContent);
    res.end();
}
function resImage(res){
    var imgContent = fs.readFileSync(iconParh);
    res.writeHead(200, {"Content-Type": "image/png"});
    res.write(imgContent);
    res.end();
}
function showlist(res){
    var dirPath = path.join(__dirname, "/fileDir");
    var files = fs.readdirSync(dirPath);
    var fileList = [];
    for(var i = 0; i<files.length; i++){
        var filePath = path.join(dirPath, "/"+files[i]);
        var fileObj = fs.statSync(filePath);
        var obj = {};
        obj.fileName = files[i];
        obj.fileTime = fileObj.ctimeMs;
        obj.fileSize = fileObj.size;
        obj.fileType = fileObj.isFile() ? "file"  : "folder";
        fileList.push(obj);
    }
    var jsonStr = JSON.stringify(fileList);
    res.writeHead(200, {"Content-Type": "text/plain"});
    res.write(jsonStr);
    res.end();
}
function deleteFile(argObj,res){
    //console.log(argObj);
    var delId = argObj.delId;
    var dirPath = path.join(__dirname,"/fileDir");
    var files = fs.readdirSync(dirPath);
    for(var i=0;i<files.length;i++){
        var fileObj = fs.statSync(path.join(dirPath+"/"+files[i]));
        if(delId.indexOf(fileObj.ctimeMs)>0){
            fs.unlinkSync(path.join(dirPath+"/"+files[i]));
            res.end("success");
            break;
        }
    }

}
http.createServer((req,res)=>{
    //req.url指端口或者域名之后的部分
    //http://localhost:8081/pathname?delID=1532846&pagrID=10
    var urlStr = req.url;
    var urlObj = parseUrl(urlStr);
    router(urlObj, req, res);
}).listen(8081);

console.log("server is listening 8081");